<template>
  <view class="add-pet-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{paddingTop: statusBarHeight + 'px'}">
      <view class="navbar-content">
        <view class="back-btn" @tap="goBack">
          <text class="iconfont">←</text>
        </view>
        <text class="navbar-title">添加宠物</text>
        <view class="placeholder"></view>
      </view>
    </view>

    <scroll-view scroll-y class="content-scroll">
        <!-- 上传照片 -->
        <view class="form-card">
          <text class="form-title">宠物照片</text>
          <view class="photo-upload">
            <view class="upload-area" @tap="chooseImage">
              <image v-if="petPhoto" :src="petPhoto" mode="aspectFill" class="preview-image"></image>
              <view v-else class="upload-placeholder">
                <text class="upload-icon">📷</text>
                <text class="upload-text">点击上传照片</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 基本信息 -->
        <view class="form-card">
          <view class="form-header">
            <text class="form-title">📋 基本信息</text>
          </view>
          
          <view class="form-item">
            <text class="form-label">宠物名称 <text class="required">*</text></text>
            <input v-model="formData.name" 
                   class="form-input" 
                   placeholder="给你的宠物起个名字" 
                   placeholder-class="input-placeholder" />
          </view>

          <view class="form-item">
            <text class="form-label">宠物类型 <text class="required">*</text></text>
            <picker mode="selector" :range="petTypes" @change="onTypeChange">
              <view class="picker-view">
                <text :class="formData.type ? 'picker-selected' : 'picker-placeholder'">
                  {{ formData.type || '请选择宠物类型' }}
                </text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="form-label">品种</text>
            <input v-model="formData.breed" 
                   class="form-input" 
                   placeholder="例如：金毛寻回犬" 
                   placeholder-class="input-placeholder" />
          </view>

          <view class="form-item">
            <text class="form-label">性别</text>
            <picker mode="selector" :range="genders" @change="onGenderChange">
              <view class="picker-view">
                <text :class="formData.gender ? 'picker-selected' : 'picker-placeholder'">
                  {{ formData.gender || '请选择性别' }}
                </text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="form-label">出生日期</text>
            <picker mode="date" @change="onDateChange">
              <view class="picker-view">
                <text :class="formData.birthday ? 'picker-selected' : 'picker-placeholder'">
                  {{ formData.birthday || '选择出生日期' }}
                </text>
                <text class="picker-arrow">📅</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="form-label">体重 (kg)</text>
            <input v-model="formData.weight" 
                   class="form-input" 
                   type="digit"
                   placeholder="例如：5.5" 
                   placeholder-class="input-placeholder" />
          </view>
        </view>

        <!-- 健康信息 -->
        <view class="form-card">
          <view class="form-header">
            <text class="form-title">💗 健康信息</text>
          </view>
          
          <view class="form-item">
            <text class="form-label">是否绝育</text>
            <picker mode="selector" :range="['未绝育', '已绝育']" @change="onNeuterChange">
              <view class="picker-view">
                <text :class="formData.isNeutered !== '' ? 'picker-selected' : 'picker-placeholder'">
                  {{ formData.isNeutered === '' ? '请选择' : (formData.isNeutered ? '已绝育' : '未绝育') }}
                </text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="form-label">疫苗状态</text>
            <picker mode="selector" :range="vaccineStatus" @change="onVaccineChange">
              <view class="picker-view">
                <text :class="formData.vaccineStatus ? 'picker-selected' : 'picker-placeholder'">
                  {{ formData.vaccineStatus || '请选择疫苗状态' }}
                </text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
		  
		  <view class="form-item">
		    <text class="form-label">上次体检时间</text>
		    <picker mode="date" @change="onCheckupDateChange">
		      <view class="picker-view">
		        <text :class="formData.lastCheckup ? 'picker-selected' : 'picker-placeholder'">
		          {{ formData.lastCheckup || '选择上次体检日期' }}
		        </text>
		        <text class="picker-arrow">📅</text>
		      </view>
		    </picker>
		  </view>

          <view class="form-item">
            <text class="form-label">芯片编号</text>
            <input v-model="formData.chipNumber" 
                   class="form-input" 
                   placeholder="如已植入芯片，请填写编号" 
                   placeholder-class="input-placeholder" />
          </view>
        </view>

        <!-- 其他信息 -->
        <view class="form-card">
          <view class="form-header">
            <text class="form-title">💬 其他信息</text>
          </view>
          
          <view class="form-item">
            <text class="form-label">特殊说明</text>
            <textarea v-model="formData.notes" 
                      class="form-textarea" 
                      placeholder="记录宠物的特殊习惯、过敏史等信息"
                      placeholder-class="input-placeholder"
                      maxlength="500" />
          </view>
        </view>

        <!-- 提交按钮 -->
        <view class="submit-section">
          <button class="submit-btn" @tap="submitForm">
            <text class="btn-icon">✓</text>
            <text class="btn-text">保存宠物信息</text>
          </button>
        </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive} from 'vue'
import petApi from '@/api/pet.js'; 
import { onLoad } from '@dcloudio/uni-app'; // 从uni-app中导入onLoad


const formData = reactive({
  ownerId: '',
  name: '',
  type: '',
  breed: '',
  gender: '',
  birthday: '',
  weight: '',
  isNeutered: '',
  vaccineStatus: '',
  chipNumber: '',
  notes: '',
  lastCheckup: '',
  avatar:'',
})

// 页面加载时获取路由参数并请求数据
onLoad((options) => {
  // 接收从我的页面传递的 ownerId
  const ownerId = options.ownerId;
  console.log('添加宠物页面获取到的ownerId:', ownerId);
  formData.ownerId=ownerId;
});


console.log(formData.ownerId);
const statusBarHeight = ref(0)
const petPhoto = ref('')

const petTypes = ['狗', '猫', '兔子', '仓鼠', '鸟类', '其他']
const genders = ['公', '母']
const vaccineStatus = ['未接种', '部分接种', '已完成']




// 获取状态栏高度
const systemInfo = uni.getSystemInfoSync()
statusBarHeight.value = systemInfo.statusBarHeight || 0

const goBack = () => {
  uni.navigateBack()
}

const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      petPhoto.value = res.tempFilePaths[0]
	  console.log(petPhoto.value);
    }
  })
}

const onTypeChange = (e) => {
  formData.type = petTypes[e.detail.value]
}

const onGenderChange = (e) => {
  formData.gender = genders[e.detail.value]
}

const onDateChange = (e) => {
  formData.birthday = e.detail.value
}

const onNeuterChange = (e) => {
  formData.isNeutered = e.detail.value === 1
}

const onVaccineChange = (e) => {
  formData.vaccineStatus = vaccineStatus[e.detail.value]
}
const onCheckupDateChange = (e) => {
  formData.lastCheckup = e.detail.value
}

const submitForm = async () => {
  // 1. 表单校验（新增头像必填校验）
  if (!formData.name) {
    uni.showToast({ title: '请输入宠物名称', icon: 'none' });
    return;
  }
  if (!formData.type) {
    uni.showToast({ title: '请选择宠物类型', icon: 'none' });
    return;
  }
  if (!petPhoto.value) {
    uni.showToast({ title: '请上传宠物头像', icon: 'none' });
    return;
  }

  try {
    // 2. 显示加载状态，防止重复提交
    uni.showLoading({ title: '处理中...', mask: true });

	console.log(petPhoto.value);

    // 3. 调用OSS上传头像
    const ossUrl  = await petApi.uploadImage(petPhoto.value);
	console.log(ossUrl);
	
    // 4. 构造完整提交数据（包含OSS处理后的头像URL）
    const submitData = {
      ...formData,
      avatar: ossUrl,
      isNeutered: formData.isNeutered ? 1 : 0, // 布尔转数字
      weight: Number(formData.weight) // 字符串转数字（便于后端转 BigDecimal）
    };
	console.log(submitData);

    // 5. 提交到添加宠物接口
	console.log(submitData);
    const submitRes = await petApi.addPet(submitData);

    // 6. 提交结果处理
    if (submitRes.data.code === 200) {
          uni.showToast({ title: '宠物添加成功', icon: 'success', duration: 2000 });
          setTimeout(() => uni.navigateBack(), 2000);
        } else {
          uni.showToast({ title: submitRes.message || '添加失败', icon: 'none' });
        }
  } catch (error) {
    // 7. 错误捕获（头像上传/接口调用失败均触发）
    uni.showToast({ title: error.message || '操作失败，请重试', icon: 'none' });
    console.error('添加宠物失败:', error);
  } finally {
    // 8. 无论成功失败，都隐藏加载状态
    uni.hideLoading();
  }
};
</script>

<style scoped>
.add-pet-page {
  min-height: 100vh;
  background-color: #F5F5F5;
}

/* 自定义导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
}

.back-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  color: #FFFFFF;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #FFFFFF;
}

.placeholder {
  width: 64rpx;
}

/* 内容区域 */
.content-scroll {
  height: 100vh;
  padding-top: calc(88rpx + var(--status-bar-height));
  padding-bottom: 120rpx;
}

/* 表单卡片 */
.form-card {
  background-color: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  margin: 32rpx;
  margin-bottom: 0;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.form-header {
  margin-bottom: 24rpx;
}

.form-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

/* 照片上传 */
.photo-upload {
  display: flex;
  justify-content: center;
  padding: 24rpx 0;
}

.upload-area {
  width: 256rpx;
  height: 256rpx;
  border-radius: 50%;
  border: 8rpx dashed rgba(137, 207, 240, 0.3);
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
}

.upload-icon {
  font-size: 64rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999999;
}

/* 表单项 */
.form-item {
  margin-bottom: 32rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  display: block;
  margin-bottom: 16rpx;
}

.required {
  color: #FF3B30;
}

.form-input {
  width: 100%;
  padding: 24rpx;
  border: 1px solid #E0E0E0;
  border-radius: 16rpx;
  font-size: 28rpx;
}

.form-textarea {
  width: 100%;
  padding: 24rpx;
  border: 1px solid #E0E0E0;
  border-radius: 16rpx;
  font-size: 28rpx;
  min-height: 200rpx;
}

.input-placeholder {
  color: #CCCCCC;
}

.picker-view {
  width: 100%;
  padding: 24rpx;
  border: 1px solid #E0E0E0;
  border-radius: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.picker-placeholder {
  color: #CCCCCC;
  font-size: 28rpx;
}

.picker-selected {
  color: #333333;
  font-size: 28rpx;
}

.picker-arrow {
  color: #999999;
  font-size: 24rpx;
}

/* 提交按钮 */
.submit-section {
  padding: 32rpx;
}

.submit-btn {
  width: 100%;
  background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
  color: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  box-shadow: 0 8rpx 24rpx rgba(137, 207, 240, 0.4);
}

.btn-icon {
  font-size: 36rpx;
}
</style>